<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="common/include :: header('结算单')"></th:block>
</head>
<body  class="gray-bg">
<div class="ui-layout-east">
    <div class="container-div">
        <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="post-form">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>名称：</label>
                            <input type="text" name="name"/>
                        </li>
                        <li>
                            <label>是否套餐：</label>
                            <select name="carPackage" th:with="type=${@dict.getType('si_car_package')}">
                            <option value="">所有</option>
                            <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                        </select>
                        </li>
                        <li>
                            <label>服务类型：</label>
                            <select name="serviceCatalog" th:with="type=${@dict.getType('si_service_catalog')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        <div class="col-sm-8 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
    </div>
</div>
<div class="ui-layout-center">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="post-form1">
                    <div class="col-sm-12">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">客户姓名：</label>
                                <label class="col-sm-6 control-label">[[${statement.customerName}]]</label>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">联系方式：</label>
                                <label class="col-sm-6 control-label">[[${statement.customerPhone}]]</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">车牌号码：</label>
                                <label class="col-sm-6 control-label">[[${statement.licensePlate}]]</label>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">汽车类型：</label>
                                <label class="col-sm-6 control-label">[[${statement.carSeries}]]</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">服务类型：</label>
                                <label class="col-sm-6 control-label">[[${statement.serviceType}]]</label>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">到店时间：</label>
                                <label class="col-sm-6 control-label" th:text="${#dates.format(statement.actualArrivalTime, 'yyyy-MM-dd HH:mm')}"></label>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">总消费金额：</label>
                                <label class="col-sm-6 control-label" id="totalAmount">[[${statement.totalAmount}]]</label>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">实付价格：</label>
                                <label class="col-sm-6 control-label" id="actrallPaid">[[${statement.discountAmount}]]</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12" >
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-6 control-label">优惠价格：</label>
                                <input class="col-sm-6" type="number" onchange="discountFun()" id="discountAmount" name="discountAmount" th:field="${statement.discountAmount}"/>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <!--按钮-->
            <div class="btn-group-sm" role="group" id="MyTool" >
                <a class="btn btn-success" onclick="saveItem()">
                    <i class="fa fa-print"></i> 保存
                </a>
                <a  class="btn btn-warning" onclick="payFun()">
                    <i class="fa fa-folder-open"></i> 确认支付
                </a>
            </div>
            <div class="col-sm-8 select-table table-striped">
                <table id="statementItemTable"></table>
            </div>
        </div>
    </div>
</div>


<th:block th:include="common/include :: footer"></th:block>
<th:block th:include="common/include :: layout-latest" />
<script th:inline="javascript">
    /*左边*/
    $(function() {
        var statementId = [[${statement.id}]];
        var options = {
            id:"statementItemTable",
            toolbar:"MyTool",
            uniqueId: "itemId",//服务项的id
            url:"/business/statementItem/query?statementId="+statementId,  			 	//查询的url
            columns: [
                {
                    field: 'id',
                    title: '服务id',
                    visible: false//是否隐藏id
                },
                {
                    field: 'itemName',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'itemPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'itemQuantity',
                    title: '购买数量',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" ' +
                            'onclick="addItem(\'' + row.itemId + '\')"><i class="fa fa-plus"></i></a> ');
                        actions.push('<a class="btn btn-danger btn-xs " href="javascript:void(0)" ' +
                            'onclick="decrItem(\'' + row.itemId + '\')"><i class="fa fa-minus"></i></a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });
    $('body').layout({
        east__size:	'35%',
    });
    /*右边表格*/
    $(function() {
        var options = {
            url:"/business/serviceItem/query?saleStatus=1",  			 		//查询的url
            uniqueId:"id",
            columns: [
                {
                    field: 'id',
                    title: '服务id',
                    visible: false//是否隐藏id
                },
                {
                    field: 'itemId',
                    title: '服务单项id',
                    visible: false//是否隐藏id
                },
                {
                    field: 'name',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'originalPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'info',
                    title: '备注信息',
                    sortable: true,
                    //备注只显示5个字，其他内容省略
                    formatter: function(value, row, index) {
                        return $.table.tooltip(value, 0, "open");
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" ' +
                            'onclick="addItem(\'' + row.id + '\')"><i class="fa fa-plus"></i></a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });
    //这个id为服务单项的id
    function addItem(id) {
        //右侧，拿到我们点击+那条数据
        var rs = $('#bootstrap-table').bootstrapTable('getRowByUniqueId',id);
        //将数据追加进去，添加到左侧数据，注意要追加上itemId
        var newData = {"itemId":id,"itemName":rs.name,"itemPrice":rs.originalPrice,"itemQuantity":1}
        //根据id(服务单项id)查询左侧的数据，查看数据是否存在，不存在则添加，存在则数量加1
        var statementData = $('#statementItemTable').bootstrapTable('getRowByUniqueId',id);
        if(statementData){
            //左侧有数据，则数量加1
            $('#statementItemTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field:'itemQuantity',
                value: statementData.itemQuantity+1
            })
        }else{
            //左侧没有数据，追加数据
            $('#statementItemTable').bootstrapTable('append', newData);
        }
        discountFun();//当点击了按钮，则触发这个函数计算金额
    }
    function decrItem(id) {
        //查询点击 - 号的数据
        var statementData = $('#statementItemTable').bootstrapTable('getRowByUniqueId',id);
        //拿到这条数据做判断
        if (statementData.itemQuantity > 1) {
            //若是数量大于1.则让数量减少1
            $('#statementItemTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field:'itemQuantity',
                value: statementData.itemQuantity-1
            })
        }else{
            //否则，删除这条数据
            $('#statementItemTable').bootstrapTable('removeByUniqueId',id);
        }
        //触发
        discountFun();
    }
    function discountFun() {
        //获取左侧表格的所有数据
        var data= $('#statementItemTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});
        //定义一个总金额
        var  totalAmount=0;
        //遍历循环数据，计算出总金额
        $.each(data,function (index,item) {
            totalAmount += item.itemPrice * item.itemQuantity;
        })
        //获取优惠金额，从label中获取
        var discountAmount = $('#discountAmount').val();

        //优惠金额不能为负数，或者没有优惠金额时候设置为0
        if (discountAmount < 0 || !discountAmount) {
            $('#discountAmount').val(0);
            return;
        }//优惠金额不能比总金额大
        if (discountAmount>totalAmount) {
            $.modal.alert("优惠金额不能比总价格大");
            $('#discountAmount').val(0);
            //将总金额与实付金额相等
            //$('#actrallPaid').text(totalAmount);
            discountFun();
            return;
        }
        //判断表格中是否有数据，若是没有数据将值都设为0
        if (data.length==0) {
            $('#actrallPaid').text(0);
            $('#totalAmount').text(0);
            $('#discountAmount').val(0);
        }
        //计算出实付金额
        var actrallPaid = totalAmount - discountAmount;
        //把计算出来的内容设置在label中
        $('#actrallPaid').text(actrallPaid);
        $('#totalAmount').text(totalAmount);
    }

    function saveItem() {
        //获取折扣价格和statementId
        var discountAmount = $('#discountAmount').val();
        var statementId = [[${statement.id}]];
        //获取左侧表格的所有数据
        var data= $('#statementItemTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});
        //需要遍历数据，为其设置上statementId
        $.each(data,function (index,item) {
            item.statementId=statementId;
            console.log(item)
        })

        //在data后面加上折扣价格和statementId
        data.push({itemPrice:discountAmount,statementId:statementId});
        console.log(data)
        //发送请求到后台
        var config = {
            url: ctx + "/business/statementItem/saveItems",
            type: 'post',
            dataType: 'json',
            contentType:"application/json",
            data: JSON.stringify(data),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $("#saveBtn").addClass("disabled");
                $("#payBtn").removeClass("disabled");
                $.operate.ajaxSuccess(result);
            }
        };
        $.ajax(config)
    }

    //确认支付按钮
    function payFun() {
        //从作用域中获取statementId
        var statementId = [[${statement.id}]];
        //弹窗提醒,确认付款则发送ajax请求
        $.modal.confirm("是否确认付款?",function () {
            $.operate.get("/business/statementItem/pay?statementId="+statementId);
        })
    }
</script>
</body>
</html>